import request from '@/utils/request'

// 查询pdf列表
export function listPdf(query) {
  return request({
    url: '/system/pdf/list',
    method: 'get',
    params: query
  })
}

// 查询pdf详细
export function getPdf(id) {
  return request({
    url: '/system/pdf/' + id,
    method: 'get'
  })
}

// 新增pdf
export function addPdf(data, saveVo) {
  // 确保 saveVo 是字符串形式
  const saveVoParam = saveVo ? encodeURIComponent(JSON.stringify(saveVo)) : '';
  const url = `/system/pdf${saveVoParam ? `?saveVo=${saveVoParam}` : ''}`;
  const formData = new FormData();

  // 如果data是文件对象，直接添加到FormData
  if (data instanceof File) {
    formData.append('file', data);
  }
  // 如果data是FormData，直接使用
  else if (data instanceof FormData) {
    return uploadFormData(url, data);
  }
  // 如果data是对象，遍历添加到FormData
  else if (typeof data === 'object') {
    Object.keys(data).forEach(key => {
      // 检查是否为文件数组
      if (Array.isArray(data[key]) && data[key].length > 0 && data[key][0] instanceof File) {
        data[key].forEach(file => {
          formData.append('files', file);
        });
      }
      // 检查是否为文件对象
      else if (data[key] instanceof File) {
        formData.append('files', data[key]);
      }
      // 检查是否为文件列表（el-upload 组件返回的格式）
      else if (Array.isArray(data[key]) && data[key].length > 0 && data[key][0].raw) {
        data[key].forEach(fileItem => {
          if (fileItem.raw) {
            formData.append('files', fileItem.raw, fileItem.name);
          }
        });
      }
      // 普通字段
      else if (data[key] !== null && data[key] !== undefined) {
        formData.append(key, data[key]);
      }
    });
  }

  return uploadFormData(url, formData);
}

// 自定义FormData上传方法
function uploadFormData(url, formData) {
  return new Promise((resolve, reject) => {
    const { getToken } = require('@/utils/auth')
    const axios = require('axios')

    axios({
      url: process.env.VUE_APP_BASE_API + url,
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Bearer ' + getToken()
      }
    }).then(res => {
      // 处理响应
      const code = res.data.code || 200
      if (code === 200) {
        resolve(res.data)
      } else {
        reject(res.data.msg || '上传失败')
      }
    }).catch(err => {
      console.error('上传PDF文件出错:', err)
      reject(err.message || '上传过程中发生错误')
    })
  })
}

// 修改pdf
export function updatePdf(data) {
  return request({
    url: '/system/pdf',
    method: 'put',
    data: data
  })
}

// 删除pdf
export function delPdf(id) {
  return request({
    url: `/system/pdf/delete/${id}?ids=${id}`,
    method: 'delete'
  })
}

// 批量还原pdf
export function revertPdf(ids) {
  return request({
    url: `/system/pdf/revert/${ids}?ids=${ids}`,
    method: 'get'
  })
}
// 获取合集下拉框数据
export function listCollectionSelect(name) {
  return request({
    url: `/system/collection/select?name=${name}`,
    method: 'get'
  })
}

// 获取作曲家下拉框数据
export function listComposerSelect(name) {
  return request({
    url: `/system/composer/select?name=${name}`,
    method: 'get'
  })
}

// 获取乐器下拉框数据
export function listInstrumentSelect(name) {
  return request({
    url: `/system/instrument/select?name=${name}`,
    method: 'get'
  })
}

// 获取出版社下拉框数据
export function listPublishSelect(name) {
  return request({
    url: `/system/publish/select?nanme=${name}`,
    method: 'get'
  })
}

// 获取出版信息下拉框数据
export function listInfoSelect(id, name) {
  return request({
    url: `/system/info/select?publishId=${id}&name=${name}`,
    method: 'get'
  })
}
